package com.wonders.frame.autoGeneration.task;

import com.wonders.frame.autoGeneration.support.TaskContent;
import com.wonders.frame.autoGeneration.support.enums.ColumnTypeEnum;
import com.wonders.frame.autoGeneration.support.from.ColumnInfo;
import com.wonders.frame.autoGeneration.task.Core.Task;
import com.wonders.frame.common.util.FileUtil;
import com.wonders.frame.common.util.HumpUtil;

import java.io.File;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @author 顾乘瑞
 */
public class GenJsxTask extends Task {
    private static final String PATH = System.getProperty("file.separator") +"src"
            + System.getProperty("file.separator") + "main"
            + System.getProperty("file.separator") + "resources"
            + System.getProperty("file.separator") + "frontend"
            + System.getProperty("file.separator");

    public GenJsxTask(final TaskContent cont) {
        super(cont);
    }

    @Override
    public Object call() {
        String tableName = cont.getTableName();
        String entityClassName = HumpUtil.tableName2ClassName(tableName);
        String className = HumpUtil.lineToHump(tableName);

        String filePath = TaskContent.PROJECT_PATH + PATH;
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String writeFilePath = filePath + "/" + className + ".jsx";
        StringBuilder content = new StringBuilder("import React from 'react'\n" +
                "import {\n" +
                "    Form,\n" +
                "    Row,\n" +
                "    Col,\n" +
                "    Input,\n" +
                "    DatePicker,\n" +
                "    Modal,\n" +
                "    Popconfirm,\n" +
                "    InputNumber,\n" +
                "    message,\n" +
                "    Divider,\n" +
                "} from 'antd'\n" +
                "import MyTable from \"../common/myTable.jsx\";\n" +
                "import moment from 'moment'\n" +
                "import '../../css/common.css'\n" +
                "import AuthButton from \"../common/AuthButton.jsx\";\n" +
                "import FrameCommon from '../common/common.jsx'\n" +
                "import Constants from '../common/constants'\n" +
                "\n" +
                "const frameCommon = new FrameCommon()\n" +
                "\n" +
                "\n" +
                "\n" +
                "\n" +
                "class SearchForm extends React.Component {\n" +
                "    render() {\n" +
                "        const {getFieldDecorator} = this.props.form;\n" +
                "        return (\n" +
                "            <div className=\"searchForm\">\n");
        //查询form
        cont.getSearchForm().forEach(v -> {
            content.append(ColumnTypeEnum.valueOf(v.getType().toUpperCase()).getElement()
                    .getSearchHtml(v.getComment(),HumpUtil.lineToHump(v.getColumn())));
        });

        content.append("            </div>\n" +
                "        )\n" +
                "    }\n" +
                "}\n" +
                "\n" +
                "SearchForm = Form.create({})(SearchForm);\n" +
                "\n" +
                "const CollectionCreateForm = Form.create({name: 'form_in_modal'})(\n" +
                "    class extends React.Component {\n" +
                "        render() {\n" +
                "            const {\n" +
                "                visible, form, title, onCancel, onOk\n" +
                "            } = this.props;\n" +
                "            const {getFieldDecorator} = form;\n" +
                "\n" +
                "            return (\n" +
                "                <Modal\n" +
                "                    visible={visible}\n" +
                "                    title={title}\n" +
                "                    okText=\"保存\"\n" +
                "                    cancelText=\"关闭\"\n" +
                "                    onCancel={onCancel}\n" +
                "                    onOk={onOk}\n" +
                "                    width={800}\n" +
                "                >\n" +
                "                    <Row>\n" +
                "                        <Col offset={1} span={22}>\n" +
                "                            <Form>\n");
        //新增form
        cont.getAddForm().forEach(v -> {
            content.append(ColumnTypeEnum.valueOf(v.getType().toUpperCase()).getElement()
                    .getAddHtml(v.getComment(),HumpUtil.lineToHump(v.getColumn())));
        });

        content.append("                            </Form>\n" +
                "                        </Col>\n" +
                "                    </Row>\n" +
                "\n" +
                "                </Modal>\n" +
                "            );\n" +
                "        }\n" +
                "    }\n" +
                ");\n" +
                "\n" +
                "class " + entityClassName + " extends React.Component {\n" +
                "    state = {\n" +
                "        listUrl: frameCommon.initRequestUrl('/" + className + "/getList'),\n" +
                "        saveUrl: frameCommon.initRequestUrl('/" + className + "/save'),\n" +
                "        deleteUrl: frameCommon.initRequestUrl('/" + className + "/delete'),\n" +
                "        showModal: false,\n" +
                "        searchPageNum: 1,\n" +
                "        searchPageSize: 8,\n" +
                "        columns: [\n");

        //列表column
        cont.getListForm().forEach(v -> {
            content.append(ColumnTypeEnum.valueOf(v.getType().toUpperCase())
                    .getJs(v.getComment(),HumpUtil.lineToHump(v.getColumn())));
        });

        content.append("            {\n" +
                "                title: '操作',\n" +
                "                width: '15%',\n" +
                "                dataIndex: 'operation',\n" +
                "                render: (text, record) => (\n" +
                "                    <div>\n" +
                "                        <AuthButton type=\"primary\" shape=\"round\" size=\"small\" disabled={\"MODIFY\"}\n" +
                "                                    onClick={() => this.modifyRole(record)} text={\"修改\"}\n" +
                "                        />\n" +
                "                        <Divider type=\"vertical\"/>\n" +
                "                        <Popconfirm title=\"确定要删除吗?\" okText=\"确定\" cancelText=\"取消\"\n" +
                "                                    onConfirm={() => this.handleDelete(record)}>\n" +
                "                            <AuthButton className=\"delete_btn_class\" shape=\"round\" size=\"small\" text={\"删除\"}\n" +
                "                                        disabled={\"DELETE\"}/>\n" +
                "                        </Popconfirm>\n" +
                "                    </div>\n" +
                "                ),\n" +
                "            }],\n" +
                "        modifyData: {},\n" +
                "    };\n" +
                "\n" +
                "    //页面第一次进入就会调用\n" +
                "    componentDidMount() {\n" +
                "        //开始参数为空\n" +
                "        this.handleSearch();\n" +
                "    };\n" +
                "\n" +
                "    onRef = (ref) => {\n" +
                "        this.child = ref;\n" +
                "    };\n" +
                "\n" +
                "    //查询\n" +
                "    handleSearch = (e) => {\n" +
                "        if(e){\n" +
                "            e.preventDefault();\n" +
                "        }\n" +
                "        this.searchForm.props.form.validateFields((err, values) => {\n" +
                "            this.getList(values);\n" +
                "        });\n" +
                "    };\n" +
                "    getList = (values) => {\n");
        /*
          处理查询参数一些特殊情况
          eg. 时间
         */
        cont.getSearchForm().forEach(v -> {
            content.append(ColumnTypeEnum.valueOf(v.getType().toUpperCase()).getElement()
                    .getSearchSpecialOperate(HumpUtil.lineToHump(v.getColumn())));
        });

        content.append(
                "        values = {\n" +
                "            params: values,\n" +
                "            pageNum: this.state.searchPageNum,\n" +
                "            pageSize: this.state.searchPageSize\n" +
                "        };\n" +
                "        this.child.setLoading(true);\n" +
                "        this.child.setParams(values);\n" +
                "        frameCommon.call(Constants.POST,\n" +
                "            {\n" +
                "                url: this.state.listUrl,\n" +
                "                data: JSON.stringify(values)\n" +
                "            },\n" +
                "            (data) => {\n" +
                "                this.child.setLoading(false);\n" +
                "                this.child.setData(data);\n" +
                "            }\n" +
                "        )\n" +
                "    };\n" +
                "\n" +
                "    //拼接search查询框\n" +
                "    getFields = () => {\n" +
                "        const children = [];\n" +
                "        const {getFieldDecorator} = this.props.form;\n" +
                "        children.push(\n" +
                "            <SearchForm wrappedComponentRef={(param) => {\n" +
                "                this.searchForm = param;\n" +
                "            }}/>\n" +
                "        );\n" +
                "        return children;\n" +
                "    };\n" +
                "\n" +
                "    //清空search框\n" +
                "    handleReset = () => {\n" +
                "        this.searchForm.props.form.resetFields();\n" +
                "    };\n" +
                "\n" +
                "    //添加新增按钮\n" +
                "    getToolBar = () => {\n" +
                "        return <Row>\n" +
                "            <Col offset={0} span={6} className=\"m_toolBar\">\n" +
                "                <AuthButton type=\"primary\" size=\"small\" shape=\"round\"\n" +
                "                            onClick={this.handleAdd} icon=\"plus\" text={\"新增\"} disabled={\"ADD\"}/>\n" +
                "            </Col>\n" +
                "        </Row>\n" +
                "    };\n" +
                "\n" +
                "    //点击新增 打开新增修改modal框\n" +
                "    handleAdd = () => {\n" +
                "        this.setState({\n" +
                "            title: \"新增\",\n" +
                "            showModal: true,\n" +
                "            submitType: 'add',\n" +
                "            //清空编辑框留下来的值\n" +
                "            modifyData: {},\n" +
                "        });\n" +
                "    };\n" +
                "\n" +
                "    //点击修改\n" +
                "    modifyRole = (record) => {\n" +
                "        let formData = {\n" +
                "            ...record,\n");
        /*
          处理修改时一些特殊情况
          eg. 时间
         */
        cont.getAddForm().forEach(v -> {
            content.append(ColumnTypeEnum.valueOf(v.getType().toUpperCase()).getElement()
                    .getModifySpecialOperate(HumpUtil.lineToHump(v.getColumn())));
        });
        content.append("        };\n" +
                "        this.setState(\n" +
                "            {\n" +
                "                title: \"修改\",\n" +
                "                showModal: true,\n" +
                "                submitType: 'edit',\n" +
                "                modifyData: formData,\n" +
                "            }\n" +
                "        );\n" +
                "        this.collectionCreateForm.props.form.setFieldsValue(formData);\n" +
                "    };\n" +
                "\n" +
                "    //关闭新增修改框\n" +
                "    handleClose = () => {\n" +
                "        this.setState(\n" +
                "            {\n" +
                "                showModal: false\n" +
                "            }\n" +
                "        );\n" +
                "        this.collectionCreateForm.props.form.resetFields();\n" +
                "    };\n" +
                "\n" +
                "    //保存新增/修改\n" +
                "    handleSave = () => {\n" +
                "        const form = this.collectionCreateForm.props.form;\n" +
                "        const searchForm = this.searchForm.props.form;\n" +
                "        //判断是新增还是修改用\n" +
                "        let submitType = this.state.submitType;\n" +
                "        form.validateFields((err, values) => {\n" +
                "            if (err) {\n" +
                "                return;\n" +
                "            }\n" +
                "\n" +
                "            //因为form表单里没用id和remove字段  所以如果是编辑的话  需要把id和remove设置上去\n" +
                "            if (this.state.modifyData) {\n" +
                "                values = {\n" +
                "                    id: this.state.modifyData.id,\n" +
                "                    removed: this.state.modifyData.removed,\n" +
                "                    ...values\n" +
                "                }\n" +
                "            }\n" +
                "\n" +
                "            values = {\n" +
                "                ...values,\n");
        /*
          处理修改时一些特殊情况
          eg. 时间
         */
        cont.getAddForm().forEach(v -> {
            content.append(ColumnTypeEnum.valueOf(v.getType().toUpperCase()).getElement()
                    .getSaveSpecialOperate(HumpUtil.lineToHump(v.getColumn())));
        });
        content.append("            }\n" +
                "            frameCommon.call(Constants.POST,\n" +
                "                {\n" +
                "                    url: this.state.saveUrl,\n" +
                "                    data: JSON.stringify(values)\n" +
                "                },\n" +
                "                (data) => {\n" +
                "                    if (data.code == \"0\") {\n" +
                "                        if (submitType == \"add\") {\n" +
                "                            message.success(\"新增成功\");\n" +
                "                        } else if (submitType == \"edit\") {\n" +
                "                            message.success(\"修改成功\");\n" +
                "                        }\n" +
                "                    } else {\n" +
                "                        if (data.msg) {\n" +
                "                            message.error(data.msg);\n" +
                "                        } else {\n" +
                "                            message.error(\"系统异常\");\n" +
                "                        }\n" +
                "                    }\n" +
                "\n" +
                "                    //清空model框里的form\n" +
                "                    form.resetFields();\n" +
                "                    //清空查询框\n" +
                "                    searchForm.resetFields();\n" +
                "                    //页码回到第一页\n" +
                "                    this.child.setState({\n" +
                "                        pagination: {\n" +
                "                            current: 1\n" +
                "                        }\n" +
                "                    });\n" +
                "                    this.handleSearch();\n" +
                "                    this.setState({\n" +
                "                        searchPageNum: this.child.getPagination().current,\n" +
                "                        showModal: false\n" +
                "                    });\n" +
                "                }\n" +
                "            )\n" +
                "        });\n" +
                "    };\n" +
                "\n" +
                "    //删除\n" +
                "    handleDelete = (record) => {\n" +
                "        const searchForm = this.searchForm.props.form;\n" +
                "        frameCommon.call(Constants.GET,\n" +
                "            {\n" +
                "                url: this.state.deleteUrl,\n" +
                "                data: {\n" +
                "                    id: record.id\n" +
                "                }\n" +
                "            },\n" +
                "            (data) => {\n" +
                "                if (data.code == '0') {\n" +
                "                    message.success(\"删除成功\");\n" +
                "                } else {\n" +
                "                    message.error(\"删除成功\");\n" +
                "                }\n" +
                "                //清空查询框\n" +
                "                searchForm.resetFields();\n" +
                "                //页码回到第一页\n" +
                "                this.child.setState({\n" +
                "                    pagination: {\n" +
                "                        current: 1\n" +
                "                    }\n" +
                "                });\n" +
                "                this.handleSearch();\n" +
                "                this.setState({\n" +
                "                    searchPageNum: this.child.getPagination().current,\n" +
                "                    showModal: false\n" +
                "                });\n" +
                "            }\n" +
                "        )\n" +
                "    };\n" +
                "\n" +
                "\n" +
                "    render() {\n" +
                "        return (\n" +
                "            <div>\n" +
                "                <Form\n" +
                "                    onSubmit={this.handleSearch}\n" +
                "                >\n" +
                "                    <Row className=\"searchFormDiv\">\n" +
                "                        <Col span={24}>\n" +
                "                            <Row gutter={24}>{this.getFields()}</Row>\n" +
                "                            <Row className=\"m_searchButton\">\n" +
                "                                <Col span={24} style={{textAlign: 'center'}}>\n" +
                "                                    <AuthButton shape=\"round\" className=\"search_btn_class fs13\" disabled={\"SEARCH\"}\n" +
                "                                                htmlType=\"submit\" icon=\"search\" text={\"查询\"}/>\n" +
                "                                    <AuthButton shape=\"round\" className=\"reset_btn_class fs13\"\n" +
                "                                                style={{marginLeft: 8}} onClick={this.handleReset} icon=\"reload\"\n" +
                "                                                text={\"重置\"}\n" +
                "                                    />\n" +
                "\n" +
                "                                </Col>\n" +
                "                            </Row>\n" +
                "                        </Col>\n" +
                "                    </Row>\n" +
                "                    <MyTable onRef={this.onRef} columns={this.state.columns} listUrl={this.state.listUrl}\n" +
                "                             toolbar={this.getToolBar}/>\n" +
                "                </Form>\n" +
                "                <CollectionCreateForm\n" +
                "                    wrappedComponentRef={(param) => {\n" +
                "                        this.collectionCreateForm = param;\n" +
                "                    }}\n" +
                "                    visible={this.state.showModal}\n" +
                "                    title={this.state.title}\n" +
                "                    onCancel={this.handleClose}\n" +
                "                    onOk={this.handleSave}\n" +
                "                />\n" +
                "            </div>\n" +
                "        );\n" +
                "    }\n" +
                "}\n" +
                "\n" +
                "export default Form.create()(" + entityClassName + ")");
        FileUtil.createFile(content.toString(), writeFilePath);
        return null;
    }

}
